package application.view
{
	import application.ApplicationFacade;
	import application.model.ConfigProxy;
	import application.model.GatewayProxy;
	import application.view.components.TextArea;
	
	import flash.events.TextEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	
	import org.puremvc.interfaces.IMediator;
	import org.puremvc.interfaces.INotification;
	import org.puremvc.patterns.mediator.Mediator;
	
	public class TextAreaMediator extends Mediator implements IMediator
	{
		public static const NAME:String = "TextAreaMediator";
		
		private var gateway:GatewayProxy;
		private var config:ConfigProxy;
		
		private var url:String;
		private var email:String;
		private var activeReqeust:String;
		
		public function TextAreaMediator( viewComponent:Object )
		{
			super( viewComponent );
			
			gateway = facade.retrieveProxy( GatewayProxy.NAME ) as GatewayProxy;
			config = facade.retrieveProxy( ConfigProxy.NAME ) as ConfigProxy;
			
			tArea.addEventListener(TextEvent.LINK, handleLinks);
		}
		
		override public function getMediatorName():String
		{
			return NAME;
		}
		
		override public function listNotificationInterests():Array
		{
			return new Array( ApplicationFacade.VIEW_INIT,
							  ApplicationFacade.MODEL_CHANGED,
							  ApplicationFacade.PAGE_SELECTED );
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch ( notification.getName() )
			{
				case ApplicationFacade.VIEW_INIT:
					showPage(1);
					break;
				
				case ApplicationFacade.MODEL_CHANGED:
					showPage(1);
					break;
				
				case ApplicationFacade.PAGE_SELECTED:
					showPage( notification.getBody() as Number );
					break;
			}
		}
		
		protected function get tArea():TextArea
		{
			return viewComponent as TextArea;
		}
		
		private function showPage(value:Number):void
		{
			// Store all the posts.
			var posts:Array = gateway.posts.toArray();
			posts.reverse();
			
			// Store posts that will be displayed on page.
			var page:Array = new Array();
			
			var postsPerPage:Number = config.getData().postsPerPage;
			var startIndex:Number = (value-1) * postsPerPage;
			var endIndex:Number = startIndex + postsPerPage;
			var total:Number = posts.length;
			
			// Check if total exceeds posts length.
			if ( total < postsPerPage )
			{
				endIndex = total;
			}
			
			page = posts.slice(startIndex, endIndex);
			
			tArea.text = "";
			
			for ( var i:Number = 0; i < page.length; i++ )
			{
				var author:String;
				var message:String = page[i].message;
				var date:String = page[i].date;
				var email:String;
				
				if ( page[i].url != "" )
				{
					author = "<a href='event:" + page[i].url + "'><u>" + page[i].author + "</u></a>"
				}
				else
				{
					author = page[i].author;
				}
				
				if ( page[i].email != "" )
				{
					if ( validateEmail(page[i].email) )
					{
						email = "<font size='9' color='#b4b4b4'> | " + 
						"<a href='event:" + page[i].email + "'><u>e-mail author</u></a></font>";
					}
					else
					{
						email = "";
					}
				}
				else
				{
					email = "";
				}
				
				tArea.text += "<font size='12' color='#000000'>" + author + " said:</font>\n" +
				"<font size='11' color='#808080'><i>" + message + "</i></font>\n" + 
				"<font size='9' color='#b4b4b4'>" + date + "</font>" + email + "\n\n";
			}
		}
		
		private function handleLinks(event:TextEvent):void
		{
			var message:String;
			
			if ( event.text.indexOf("@") != -1 )
			{
				email = "mailto:" + event.text;
				message = "Do you really wish to email at: " + event.text + " ?";
				activeReqeust = "email";
			}
			else
			{
				url = "http://" + event.text;
				message = "Do you really wish to visit: http://" + event.text + " ?";
				activeReqeust = "url";
			}
			Alert.show(message, "Alert", Alert.YES | Alert.NO, null, visitURL);
		}
		
		private function visitURL(event:CloseEvent):void
		{
			switch ( event.detail )
			{
				case Alert.YES:
					var request:URLRequest;
					if ( activeReqeust == "email" )
					{
						request = new URLRequest(email);
					}
					else
					{
						request = new URLRequest(url);
					}
					navigateToURL(request);
					break;
			}
		}
		
		private function validateEmail(str:String):Boolean 
		{
            var pattern:RegExp = /(\w|[_.\-])+@((\w|-)+\.)+\w{2,4}+/;
            var result:Object = pattern.exec(str);
            
            if ( result == null )
            {
                return false;
            }
            return true;
        }
	}
}